import logging
from typing import Any, Dict

from fastapi import APIRouter, Depends, Request

from app.dependencies.auth import get_current_user, require_roles
from app.models.user import User

logger = logging.getLogger("app.error")

router = APIRouter(prefix="/users", tags=["users"])


def _get_request_id(request: Request) -> str:
    """Safely extract request ID from request state"""
    return getattr(request.state, "request_id", "unknown")


@router.get(
    "/me",
    summary="获取当前用户信息",
    description="获取当前登录用户的详细信息，需要JWT认证",
    openapi_extra={
        "x-roles": ["hr", "interviewer", "boss"],
        "security": [{"bearerAuth": []}],
    },
)
async def get_me(request: Request, current_user: User = Depends(require_roles("hr", "interviewer", "boss"))) -> Dict[str, Any]:
    """
    获取当前用户信息
    
    需要有效的JWT访问令牌，支持所有角色(hr/interviewer/boss)。
    
    返回信息包括：
    - **id**: 用户唯一标识
    - **email**: 用户邮箱地址
    - **name**: 用户姓名
    - **role**: 用户角色
    
    错误情况：
    - 无效的访问令牌
    - 令牌已过期
    - 用户权限不足
    """
    request_id = _get_request_id(request)
    logger.info("users_me_access", extra={
        "user_id": current_user.id, 
        "email": current_user.email, 
        "request_id": request_id
    })
    return {
        "id": current_user.id,
        "email": current_user.email,
        "name": current_user.name,
        "role": current_user.role,
    } 